package com.jialea.luobochat.server.config;

import com.jialea.luobochat.server.handler.JacksonObjectHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * mvc配置
 *
 * @author: wf
 * @created: 2024/7/19 23:23
 */

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * 跨域
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*") // 允许所有源访问，可以指定具体的源
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
                .allowedHeaders("*") // 允许所有请求头
                .allowCredentials(false) // 是否允许发送Cookie
                .maxAge(3600); // 预检请求的有效期，单位为秒
    }

    /**
     * mvc框架消息转换器
     * 解决Long类型前端精度丢失问题
     *
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        //创建消息转换器对象
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new
                MappingJackson2HttpMessageConverter();
        //设置对象转换器
        mappingJackson2HttpMessageConverter.setObjectMapper(new JacksonObjectHandler());
        //添加到容器中
        converters.add(0, mappingJackson2HttpMessageConverter);
    }
}
